﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Titan
{
    /// <summary>
    /// 实体类型，考虑到多个不同类型的类都可能实现IDynamicEntity
    /// </summary>
    public class EntityType
    {
        #region 构造函数
        public EntityType(Type type, string typeName)
        {
            if (!typeof(IDynamicEntity).IsAssignableFrom(type))
            {
                throw new ArgumentException("非IDynamicEntity类型不能使用此构造方法，请使用另外一个无typeName参数的重载构造方法", "typeName");
            }
            this.Type = type;
            this.TypeName = typeName;
            this.isDynamicEntity = true;
        }

        public EntityType(Type type)
        {
            if (typeof(IDynamicEntity).IsAssignableFrom(type))
            {
                throw new ArgumentException("IDynamicEntity类型不能使用此构造方法，请使用另外一个带typeName参数的重载构造方法", "type");
            }
            this.Type = type;
            this.TypeName = type.FullName;
            this.isDynamicEntity = false;
        }
        public EntityType(object obj)
        {
            this.Type = obj.GetType();
            if (obj is IDynamicEntity)
            {
                this.TypeName = ((IDynamicEntity)obj).TypeName;
                this.isDynamicEntity = true;
            }
            else
            {
                this.TypeName = this.Type.FullName;
                this.isDynamicEntity = false;
            }
        }
        #endregion

        #region 属性
        public string TypeName { get; set; }
        public Type Type { get; set; }
        #endregion

        private bool isDynamicEntity;

        public object CreateInstance()
        {
            object obj=Activator.CreateInstance(this.Type);
            if (isDynamicEntity)
            {
                ((IDynamicEntity)obj).TypeName = TypeName;
            }
            return obj;
        }

        #region override
        public override bool Equals(object obj)
        {
            if (isDynamicEntity)
            {
                return TypeName.ToLower().Equals(((EntityType)obj).TypeName.ToLower());
            }
            else
            {
                return Type.Equals(((EntityType)obj).Type);
            }

        }
        public override int GetHashCode()
        {
            if (isDynamicEntity)
            {
                return TypeName.ToLower().GetHashCode();
            }
            else
            {
                return Type.GetHashCode();
            }
        }
        public override string ToString()
        {
            return TypeName + ":" + Type.ToString();
        }
        #endregion
    }
}
